package com.badboy.servlet;

import com.alibaba.fastjson2.JSON;
import com.badboy.entity.Forums;
import com.badboy.entity.Posts;
import com.badboy.entity.Users;
import com.badboy.service.ForumService;
import com.badboy.service.PostService;
import com.badboy.util.Logs;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {
    private ForumService forumService = new ForumService();
    private PostService postService = new PostService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取session
        HttpSession httpSession = req.getSession();



        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        String action = req.getParameter("action");
        Logs.logger.info(action);
        Map<String, Object> result = new HashMap<>();

        try {
            if ("getForums".equals(action)) {
                // 获取所有版块
                List<Forums> forums = forumService.getAllForums();
                result.put("success", true);
                result.put("data", forums);
            } else if ("getForumById".equals(action)) {
                // 根据ID获取版块
                Integer forumId = Integer.parseInt(req.getParameter("forumId"));
                Forums forum = forumService.getForumById(forumId);
                result.put("success", true);
                result.put("data", forum);
            } else if ("addForum".equals(action)) {
                // 添加新版块
                Forums forum = new Forums();
                forum.setName(req.getParameter("name"));
                forum.setDescription(req.getParameter("description"));
                forum.setAdminId(Integer.parseInt(req.getParameter("adminId")));
                forum.setCreatedAt(new java.util.Date());

                boolean success = forumService.addForum(forum);
                result.put("success", success);
                if (success) {
                    result.put("message", "版块添加成功");
                    result.put("forumId", forum.getForumId());
                } else {
                    result.put("message", "版块添加失败");
                }
            } else if ("getPosts".equals(action)) {
                // 获取帖子列表
                Integer forumId = req.getParameter("forumId") != null ?
                        Integer.parseInt(req.getParameter("forumId")) : null;
                String sortType = req.getParameter("type") != null ?
                        req.getParameter("type") : "new";
                int page = req.getParameter("page") != null ?
                        Integer.parseInt(req.getParameter("page")) : 1;
                int pageSize = 10;

                List<Posts> posts = postService.getPosts(forumId, sortType, page, pageSize);
                int totalCount = forumId != null ? postService.countPosts(forumId) : 0;

                result.put("success", true);
                result.put("data", posts);
                result.put("total", totalCount);
                result.put("hasMore", (page * pageSize) < totalCount);
            } else if ("searchPosts".equals(action)) {
                //根据内容查询
                Integer forumId = req.getParameter("forumId") != null ?
                        Integer.parseInt(req.getParameter("forumId")) : null;
                String keyword = req.getParameter("keyword");
                String sortType = req.getParameter("type") != null ?
                        req.getParameter("type") : "new";

                List<Posts> posts = postService.searchPostsByContent(forumId, keyword, sortType);

                result.put("success", true);
                result.put("data", posts);

            } else if ("checkLogin".equals(action)){
                // 获取session
                Users user = (Users) httpSession.getAttribute("user");
                if (user != null) {
                    result.put("success", true);
                    result.put("user", user);
                    result.put("email",  user.getEmail());
                    result.put("message", "已登录");
                } else {
                    result.put("success", false);
                    result.put("message", "未登录");
                }
            } else if ("logout".equals(action)){
                // 清除session
                httpSession.invalidate();

            }else {
                result.put("success", false);
                result.put("message", "无效的操作类型");
            }
        } catch (NumberFormatException e) {
            result.put("success", false);
            result.put("message", "参数格式错误");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "服务器内部错误: " + e.getMessage());
        }

        try (PrintWriter out = resp.getWriter()) {
            out.print(JSON.toJSONString(result));
        }

    }


}